package com.saas.demo.config;

import com.saas.demo.comman.CommonConst;
import com.saas.demo.comman.CommonParam;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.EmptyInterceptor;
import org.springframework.context.annotation.Configuration;

/**
 * @program: demo
 * @description:
 * @author: guoxh
 * @create: 2019-01-25 15:16
 **/
@Configuration
@Slf4j
public class JpaInterceptor extends EmptyInterceptor {

    @Override
    public String onPrepareStatement(String sql) {
        Integer tenantId = CommonParam.getInstance().getTenantId();
        //租户Id小于等于0，租户ID错误，直接返回sql
        if (tenantId <= 0) {
            return sql;
        }
        for (String tableName : CommonConst.SPLIT_TABLE_LIST) {
            if (sql.contains(tableName)) {
                sql = sql.replace(tableName, tableName + "_" + tenantId);
            }
        }
        return sql;
    }
}
